package com.yyaccp.easybuy.security.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements Serializable, UserDetails {
    private String username;
    private String password;
    private String captcha;
    // 角色列表
    private List<String> roles = new ArrayList<>();
    // 资源权限列表
    private List<String> perms = new ArrayList<>();
    // 通过url判断权限
    private List<String> urls = new ArrayList<>();

    public LoginUser(String username, String password, String captcha, List<String> roles, List<String> perms) {
        this.username = username;
        this.password = password;
        this.captcha = captcha;
        this.roles = roles;
        this.perms = perms;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // @PreAuthorize("hasAuthority('user:list')")
        List<SimpleGrantedAuthority> permsList = perms.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        // @PreAuthorize("hasRole('admin')")，需要添加ROLE_前缀
        List<SimpleGrantedAuthority> roleList = roles.stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role)).collect(Collectors.toList());
        // 合并两个权限
        permsList.addAll(roleList);
        return permsList;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
